package com.le.high.class4;

import org.junit.Test;

/**
 * 给定一个字符串str，求最长的回文子串。注意区分子序列和子串的不同
 * 逆序求最长公共子序列
 */
public class Problem02_1_PalindromeSubChuan {

    public static String maxLen1(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }
        char[] s1 = str.toCharArray();
        char[] s2 = reverse(s1);
        int[][] dp = getDp(s1, s2);
        int end = 0;
        int max = 0;
        for (int i = 0; i < s1.length; i++) {
            for (int j = 0; j < s2.length; j++) {
                if (dp[i][j] > max) {
                    max = dp[i][j];
                    end = i;
                }
            }
        }
        return str.substring(end - max + 1, end + 1);
    }

    public static char[] reverse(char[] s) {
        char[] res = new char[s.length];
        for (int i = 0; i < s.length; i++) {
            res[i] = s[s.length - 1 - i];
        }
        return res;
    }

    public static int[][] getDp(char[] str1, char[] str2) {
        int[][] dp = new int[str1.length][str2.length];
        dp[0][0] = str1[0] == str2[0] ? 1 : 0;
        for (int i = 1; i < str1.length; i++) {
            dp[i][0] = str1[i] == str2[0] ? 1 : 0;
        }
        for (int i = 1; i < str2.length; i++) {
            dp[0][i] = str1[0] == str2[i] ? 1 : 0;
        }
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                dp[i][j] = str1[i] == str2[j] ? dp[i - 1][j - 1] + 1 : 0;
            }
        }
        return dp;
    }

    @Test
    public void test() {
        String test = "abcbc";
        System.out.println(maxLen1(test));
    }
}
